package com.dailyblue.java.project.shoppingcart.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.project.shoppingcart.feign.AlipayService;
import com.dailyblue.java.project.shoppingcart.feign.BooksFeign;
import com.dailyblue.java.project.shoppingcart.feign.UsersFeign;
import com.dailyblue.java.project.shoppingcart.service.ShoppingCartService;
import com.dailyblue.java.project.shoppingcart.util.JsonResult;
import com.dailyblue.java.project.shoppingcart.util.ResultCode;
import com.dailyblue.java.project.shoppingcart.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UsersFeign usersFeign;
    @Resource
    private BooksFeign booksFeign;
    @Resource
    private AlipayService alipayService;

    @Override
    public JsonResult showCart(String token) {
        log.info("token:{}", token);
        int id = Integer.parseInt(usersFeign.getUserId(token).getData().toString());
        log.info("查看{}的购物车信息", id);
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        String v = hash.get("SHOPPING_CART", id + "");
        log.info("{}的购物信息：{}", id, v);
        Map<String, Integer> map = JSONArray.parseObject(v, Map.class);
        log.info("转换之后的内容：{}", map);
        List<Map> list = new ArrayList<>();
        Set<String> set = map.keySet();
        double all = 0;
        for (String bookId : set) {
            int num = map.get(bookId);
            JsonResult jr = booksFeign.findBookById(Integer.parseInt(bookId));
            double price = Double.parseDouble(jr.getMessage());
            Map m = new HashMap();
            m.put("num", num);
            m.put("book", jr);
            list.add(m);
            all += price * num;
        }
        JsonResult result = ResultTool.success(list);
        result.setMessage(all + "");
        return result;
    }

    @Override
    public JsonResult updateCart(int bookId, int num, String token) {
        int id = Integer.parseInt(usersFeign.getUserId(token).getData().toString());
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        String v = hash.get("SHOPPING_CART", id + "");
        Map<String, Integer> map = JSONArray.parseObject(v, Map.class);
        map.put(bookId + "", num);
        hash.put("SHOPPING_CART", id + "", JSONArray.toJSONString(map));
        return showCart(token);
    }

    @Override
    public JsonResult addCart(int bookId, int num, String token) {
        log.info("token:{}", token);
        int id = Integer.parseInt(usersFeign.getUserId(token).getData().toString());
        // 这个用户的图书是否是第一次存放
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        String v = hash.get("SHOPPING_CART", id + "");
        Map<String, Integer> map;
        if (v == null) {
            map = new HashMap();
            map.put(bookId + "", num);
        } else {
            map = JSONArray.parseObject(v, Map.class);
            // 判断这本图书是否已经加入购物车
            boolean b = map.containsKey(bookId + "");
            if (b) {
                map.put(bookId + "", map.get(bookId + "") + num);
            } else {
                map.put(bookId + "", num);
            }
        }
        hash.put("SHOPPING_CART", id + "", JSONArray.toJSONString(map));
        return ResultTool.success(bookId + "加入购物车成功！");
    }

    public JsonResult addCart(String sessionId, int bookId, int num) {
        log.info("开始加入购物车,sessionId:{},bookId:{},num:{}", sessionId, bookId, num);
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        Map<String, String> map = hash.entries("SHOPPING_CART");
        log.info("map:{}", map);
        if (map == null) {
            hash.put("SHOPPING_CART", sessionId + "," + bookId, num + "");
            return ResultTool.success(ResultCode.SUCCESS);
        }
        String value = map.get(sessionId + "," + bookId);
        log.info("value:{}", value);
        if (value == null) {
            hash.put("SHOPPING_CART", sessionId + "," + bookId, num + "");
            return ResultTool.success(ResultCode.SUCCESS);
        } else {
            int n = Integer.parseInt(value);
            hash.put("SHOPPING_CART", sessionId + "," + bookId, num + n + "");
            return ResultTool.success(ResultCode.SUCCESS);

        }
    }

    @Override
    public void pay(String token) {
        log.info("开始进入付款操作");
        int userId = Integer.parseInt(usersFeign.getUserId(token).getData().toString());
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        String v = hash.get("SHOPPING_CART", userId + "");
        Map<String, Integer> map = JSONArray.parseObject(v, Map.class);
        // 1. 订单编号 自动生成
        String uuid = System.currentTimeMillis() + "" + (int) (Math.random() * 1000 + 1);
        // 2. 订单名称 用户名+日期的订单
        String name = userId + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        // 3. 订单金额
        double total = Double.parseDouble(showCart(token).getMessage());
        // 4. 订单描述 所有商品{}
        StringBuilder body = new StringBuilder("");
        Set<String> set = map.keySet();
        for (String s : set) {
            int bookId = Integer.parseInt(s);
            double pric = Double.parseDouble(booksFeign.findBookById(bookId).getMessage());
            body.append(bookId + "," + pric + ";");
        }
        log.info("生成的内容分别是：{},{},{},{}", uuid, name, total, body);
        alipayService.pay(uuid + "", name, total + "", body.toString());
    }
}
